#include "chooselevelscene.h"

ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent)
{
    // 窗体设置，同主窗口
    this->setFixedSize(480, 788);
    this->setWindowIcon(QIcon(":/image/res/Coin0001.png"));
    this->setWindowTitle("Choose Level");

    // 创建菜单栏（你也可以用ui界面设计）
    QMenuBar *menu = menuBar();
    setMenuBar(menu);
    // 创建开始菜单
    QMenu *start = menu->addMenu("开始");
    QAction *quit = start->addAction("退出");

    connect(quit, &QAction::triggered, this, &ChooseLevelScene::close);

    // 返回按钮音效
    QSound *backSound = new QSound(":/sound/res/BackButtonSound.wav", this);

    // 创建返回按钮
    MyPushButton *btn_back = new MyPushButton(":/image/res/BackButton.png",
                                              ":/image/res/BackButtonSelected.png");
    btn_back->setParent(this);
    btn_back->move(this->width() - btn_back->width(), this->height() - btn_back->height());

    // 发出信号，告知主场景返回
    connect(btn_back, &MyPushButton::clicked, this, [=]() {
        backSound->play();
        emit BackToMenu();
    });

    // 选择关卡按钮音效
    QSound *chooseSound = new QSound(":/sound/res/TapButtonSound.wav", this);

    // 创建关卡按钮
    for (int i = 0; i < 20; i++) {
        MyPushButton *levelbtn = new MyPushButton(":/image/res/LevelIcon.png");
        levelbtn->setParent(this);
        levelbtn->move(100 + (i % 4) * 70, 250 + (i / 4) * 70);

        connect(levelbtn, &MyPushButton::clicked, this, [=]() {
            chooseSound->play();
            // 实例化关卡
            QTimer::singleShot(300, this, [=]() {
                this->hide();
                // 传入关卡名（第几关）
                gameScene = new GameScene(i + 1);
                gameScene->setGeometry(this->geometry());
                gameScene->show();

                // 接收关卡返回信号
                // 注意由于gameScene在点击后才创建，因此不能写在外部
                connect(gameScene, &GameScene::BacktoSelect, this, [=]() {
                    QTimer::singleShot(300, this, [=]() {
                        this->setGeometry(gameScene->geometry());
                        this->show();
                        delete gameScene;
                        gameScene = NULL;
                    });
                });
            });
        });

        QLabel *label = new QLabel(QString::number(i + 1), levelbtn);
        label->setFixedSize(levelbtn->width(), levelbtn->height());
        label->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
        // 在鼠标点击时，穿过Label，点击btn
        label->setAttribute(Qt::WA_TransparentForMouseEvents, true);
    }
}

void ChooseLevelScene::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pic;
    pic.load(":/image/res/OtherSceneBg.png");
    painter.drawPixmap(0, 0, this->width(), this->height(), pic);

    pic.load(":/image/res/Title.png");
    painter.drawPixmap((this->width() - pic.width()) * 0.5, 100, pic.width(), pic.height(), pic);
}
